package top.eggcode.setup.config.query;

import org.hibernate.Session;
import org.springframework.stereotype.Component;
import top.eggcode.common.error.ApplicationException;
import top.eggcode.plugins.query.def.SingleRepository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Optional;

/**
 * Title: DML工具
 * Description: TODO
 * Date: 2021/3/30 9:45
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Component
public class HibernateRepository implements SingleRepository<Object> {

    @PersistenceContext
    protected EntityManager manager;

    protected Session getSession() {
        return manager.unwrap(Session.class);
    }

    @Override
    public Optional<Object> select(Class<Object> entityClass, String id) {
        if (id == null) {
            throw new ApplicationException("参数：id，不能为空！");
        }
        return Optional.ofNullable(manager.find(entityClass, id));
    }

    @Override
    public void insert(Object entity) {
        manager.persist(entity);
    }

    /**
     * 更新数据
     * 只针对未被JPA容器管理的实体
     *
     * @param entity 实体
     * @param <?>    ClassType
     */
    @Override
    public void update(Object entity) {
        manager.merge(entity);
        manager.flush();
    }

    @Override
    public void delete(Object entity) {
        manager.remove(entity);
    }
}
